<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>搜索框自动提示</title>
    <style>
      #my {
        padding-left: 10px;
        width: 50%;
        height: 33px;
      }

      ul {
        display: none;
        height: 300px;
        position: absolute;
        width: 50%;
        overflow: auto;
        list-style-type: none;
        /* list-style: none; */
        padding: 0;
      }

      ul > li {
        /* background: antiquewhite; */
        height: 50px;
        /* text-decoration: none; */
        width: 100%;
      }

      .header {
        background-color: #afa6b8f5;
      }

      a {
        box-sizing: border-box;
        line-height: 50px;
        border: 1px solid red;
        display: inline-block;
        text-decoration: none;
        width: 100%;
        height: 100%;
        background-color: #73786f;
        color: #fff;
        padding-left: 18px;
      }
      a:hover {
        opacity: 0.8;
      }
    </style>
  </head>

  <body>
    <input
      type="text"
      id="my"
      onkeyup="myFunction(this)"
      placeholder="搜索..."
    />

    <ul id="myUL">
      <li><a href="#" class="header">A</a></li>
      <li><a href="#">Adele</a></li>
      <li><a href="#">Agnes</a></li>

      <li><a href="#" class="header">B</a></li>
      <li><a href="#">Billy</a></li>
      <li><a href="#">Bob</a></li>

      <li><a href="#" class="header">C</a></li>
      <li><a href="#">Calvin</a></li>
      <li><a href="#">Christina</a></li>
      <li><a href="#">Cindy</a></li>
    </ul>
    <script>
      var as = document.getElementsByTagName("a");
      var my = document.getElementById("my");
      var ul = document.getElementById("myUL");
      let lis = document.getElementsByTagName("li");
      my.onfocus = function () {
        ul.style.display = "block";
      };
      for (let item of as) {
        item.onclick = function () {
          my.value = item.innerText;
          ul.style.display = "";
        };
      }
      function myFunction(event) {
        let content = event.value;
        for (let im of lis) {
          let str = im.getElementsByTagName("a")[0].innerHTML;
          if (str.toLowerCase().indexOf(content.toLowerCase()) > -1) {
            im.style.display = "";
          } else {
            im.style.display = "none";
          }
        }
      }
    </script>
  </body>
</html>
